package com.security.brows.ui

import android.content.Context
import android.content.Intent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.hub.videobrowsdownload.BrowsApplication
import com.security.brows.base.SecurityBaseActivity
import com.security.brows.room.BrowsRoomHelper
import com.security.brows.room.BrowsWebFavoriteBean
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SecurityBrowsHomeActivity : SecurityBaseActivity() {

    companion object {
        fun start(context: Context, fromWeb:Int = 0) {
            context.startActivity(Intent(context, SecurityBrowsHomeActivity::class.java).apply {
                putExtra("fromWeb", fromWeb)
            })
        }
    }

    val fromWeb by lazy {
        intent.getIntExtra("fromWeb", 0)
    }

    override fun preContent() {
        BrowsApplication.browsMyViewModel.onCreate(applicationContext)
        super.preContent()
    }

    override fun onStart() {
        super.onStart()
        SecurityBrowsGuideActivity.start(this, false)
    }

    override fun onDestroy() {
        if (fromWeb == 0) {
            BrowsApplication.browsMyViewModel.onDestroy()
        }
        super.onDestroy()
    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    override fun ComposeContent(
        isDarkTheme: Boolean,
        colorsScheme: SecurityBrowsColorsScheme,
        drawableScheme: SecurityBrowsDrawable
    ) {

        val stateFavorite = rememberLazyGridState()
        val stateDownloading = rememberLazyListState()
        val state = rememberLazyListState()
        val favoriteSelect = remember {
            mutableStateMapOf<String, BrowsWebFavoriteBean>()
        }
        val list =
            BrowsRoomHelper.getDao(this).getWebFavoriteFlow().collectAsState(initial = emptyList())
        val rememberPagerState = remember {
            mutableStateOf( if (fromWeb == 0) 0 else 1)
        }
        val scope = rememberCoroutineScope()
        val downloadingSize = BrowsApplication.browsMyViewModel.downloadingTaskSize.observeAsState()
        val downloadedVideoList = BrowsRoomHelper.getDao().getDownloadedVideoFlow().collectAsState(
            initial = emptyList()
        )
        val displayItemTitle = remember {
            mutableStateOf(1)
        }
        Column(
            Modifier
                .fillMaxSize()
                .background(colorsScheme.browsBg)
        ) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(60.dp)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(50.dp)
                        .clickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple()) {
                            if (favoriteSelect.isNotEmpty()) {
                                favoriteSelect.clear()
                            } else {
                                finish()
                            }
                        }
                ) {
                    Image(
                        painter = painterResource(id = drawableScheme.back),
                        contentDescription = null,
                        modifier = Modifier
                            .align(
                                Alignment.Center
                            )
                            .size(20.dp)
                    )
                }
                Text(
                    text = if (rememberPagerState.value == 0) "Browser" else if (rememberPagerState.value == 1) "Progress" else "Downloads",
                    color = colorsScheme.homeTitle,
                    fontSize = 20.sp,
                    modifier = Modifier
                        .weight(1f)
                        .align(Alignment.CenterVertically)
                        .combinedClickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple(), onLongClick = {
                            try {
                                BrowsApplication.browsMyViewModel.isDarkTheme.value =
                                    !BrowsApplication.browsMyViewModel.isDarkTheme.value!!
                            } catch (e: Exception) {
                            }
                        }) {
                            if (displayItemTitle.value == 0) {
                                displayItemTitle.value = 1
                            }else{
                                displayItemTitle.value = 0
                            }
                        }
                )
                Box(
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(50.dp)
                        .clickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple()) {
                            SecurityBrowsHistoryActivity.start(this@SecurityBrowsHomeActivity)
                        }
                ) {
                    Image(
                        painter = painterResource(id = drawableScheme.history_icon),
                        contentDescription = null,
                        modifier = Modifier
                            .align(
                                Alignment.Center
                            )
                            .size(20.dp)
                    )
                }
            }
            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(12.dp)
                    .background(colorsScheme.homeTitleSpace)
            )

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {

                if (rememberPagerState.value == 0) {
                    ComposeVpPage(colorsScheme, drawableScheme, favoriteSelect, list, stateFavorite)
                } else if (rememberPagerState.value == 1) {
                    ComposeVpProgress(downloadingSize, colorsScheme, drawableScheme, stateDownloading, displayItemTitle)
                } else if (rememberPagerState.value == 2) {
                    ComposeVpDownloaded(downloadedVideoList, colorsScheme, drawableScheme, state, displayItemTitle)
                }

            }

            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.dp)
                    .background(colorsScheme.homeTabSpace)
            )

            if (favoriteSelect.isEmpty()) {
                Row(
                    modifier = Modifier
                        .height(60.dp)
                        .background(colorsScheme.homeTabBg)
                ) {
                    if (fromWeb == 0) {
                        TableItem(
                            scope,
                            rememberPagerState,
                            0,
                            drawableScheme.tab_page_p,
                            drawableScheme.tab_page_n,
                            "Page",
                            colorsScheme,
                            null
                        )
                    }
                    TableItem(
                        scope,
                        rememberPagerState,
                        1,
                        drawableScheme.tab_pro_p,
                        drawableScheme.tab_pro_n,
                        "Progress",
                        colorsScheme,
                        downloadingSize.value
                    )
                    TableItem(
                        scope,
                        rememberPagerState,
                        2,
                        drawableScheme.tab_down_p,
                        drawableScheme.tab_down_n,
                        "Downloads",
                        colorsScheme,
                        downloadedVideoList.value.size
                    )
                }
            } else {
                val openAlertDialog = remember { mutableStateOf(false) }

                BackHandler {
                    favoriteSelect.clear()
                }
                Row(
                    modifier = Modifier
                        .height(60.dp)
                        .background(colorsScheme.homeTabBg)
                ) {
                    if (favoriteSelect.size == 1) {
                        FavoriteTableItem(
                            drawableScheme.favorite_rename,
                            "Rename",
                            colorsScheme.homeTitle
                        ) {
                            openAlertDialog.value = true
                        }
                    }
                    FavoriteTableItem(
                        drawableScheme.favorite_delete,
                        "Delete",
                        colorsScheme.homeTitle
                    ) {
                        scope.launch {
                            withContext(Dispatchers.IO) {
                                for (i in favoriteSelect.values) {
                                    i.delete(context = this@SecurityBrowsHomeActivity)
                                }
                                favoriteSelect.clear()
                            }
                        }
                    }
                }

                if (openAlertDialog.value) {
                    val item = favoriteSelect.values.firstOrNull()
                    if (item != null) {
                        var text by remember { mutableStateOf("") }

                        Dialog(onDismissRequest = { openAlertDialog.value = false }) {
                            // Draw a rectangle shape with rounded corners inside the dialog
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                shape = RoundedCornerShape(16.dp),
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth(),
                                    verticalArrangement = Arrangement.Center,
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                ) {
                                    Text(
                                        text = "Rename",
                                        modifier = Modifier.padding(16.dp),
                                        maxLines = 1
                                    )
                                    OutlinedTextField(
                                        value = text,
                                        onValueChange = { text = it },
                                        label = { Text("Name") },
                                        singleLine = true,
                                        modifier = Modifier
                                            .padding(horizontal = 16.dp)
                                            .fillMaxWidth()
                                    )
                                    Row(
                                        modifier = Modifier
                                            .padding(top = 16.dp)
                                            .fillMaxWidth(),
                                        horizontalArrangement = Arrangement.Center,
                                    ) {
                                        TextButton(
                                            onClick = { openAlertDialog.value = false },
                                            modifier = Modifier.padding(8.dp),
                                        ) {
                                            Text("Dismiss")
                                        }
                                        TextButton(
                                            onClick = {
                                                scope.launch {
                                                    item.title = text
                                                    BrowsRoomHelper.getDao().insert(item)
                                                }
                                                openAlertDialog.value = false },
                                            modifier = Modifier.padding(8.dp),
                                        ) {
                                            Text("Confirm")
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    @Composable
    private fun RowScope.FavoriteTableItem(
        iconN: Int,
        name: String,
        color: Color,
        clickAble: () -> Unit,
    ) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .weight(1f)
        ) {

            Column(
                Modifier
                    .fillMaxSize()
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple(), onClick = clickAble),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {

                Image(
                    painter = painterResource(id = iconN),
                    contentDescription = null,
                    modifier = Modifier.size(28.dp)
                )
                Spacer(modifier = Modifier.height(2.dp))
                Text(
                    text = name,
                    fontSize = 12.sp,
                    color = color
                )
            }


        }
    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    private fun RowScope.TableItem(
        scope: CoroutineScope,
        rememberPagerState: MutableState<Int>,
        pageIndex: Int,
        iconP: Int,
        iconN: Int,
        name: String,
        colorsScheme: SecurityBrowsColorsScheme,
        toastNumber: Int?
    ) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .weight(1f)
        ) {

            Column(
                Modifier
                    .fillMaxSize()
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        rememberPagerState.value = pageIndex
                    },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {

                Image(
                    painter = painterResource(id = if (rememberPagerState.value == pageIndex) iconP else iconN),
                    contentDescription = null,
                    modifier = Modifier.size(28.dp)
                )
                Spacer(modifier = Modifier.height(2.dp))
                Text(
                    text = name,
                    fontSize = 12.sp,
                    color = if (rememberPagerState.value == pageIndex) colorsScheme.homeTableSelect else colorsScheme.homeTable
                )
            }

            if (toastNumber != null && toastNumber > 0) {
                Box(
                    modifier = Modifier
                        .padding(start = 20.dp)
                        .align(Alignment.TopCenter)
                        .background(
                            Color.Red, CircleShape
                        )
                        .padding(horizontal = 4.dp)
                ) {
                    Text(text = toastNumber.toString(), fontSize = 10.sp, color = Color.White)
                }
            }
        }
    }
}